<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Models\Merchant\MerchantAdmin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class MerchantController extends Controller
{
    /**
     * 获取机构列表
     */
    public function index(Request $request)
    {
        $query = Merchant::query();

        // 搜索
        if ($request->has('name')) {
            $query->where('name', 'like', '%' . $request->name . '%');
        }

        $pageSize = $request->get('pageSize', 10);
        $pageNum = $request->get('pageNum', 1);

        // 按创建时间倒序排列
        $merchants = $query->orderBy('created_at', 'desc')->with('admins')->paginate($pageSize, ['*'], 'page', $pageNum);

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $merchants
        ], 200, ['Content-Type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 创建机构
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50',
            'tax_number' => 'nullable|string|max:100',
            'mobile' => 'nullable|string|max:255',
            'district_id' => 'nullable|integer',
            'address' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first()
            ], 400);
        }

        // 获取省市区名称（支持1-3级）
        $fullAreaname = '';
        $areaId = $request->district_id ?: ($request->city_id ?: $request->province_id);
        
        if ($areaId) {
            $address = \App\Models\Address::find($areaId);
            if ($address) {
                if ($address->level == 1) {
                    // 只选了省
                    $fullAreaname = $address->areaname;
                } elseif ($address->level == 2) {
                    // 选了市
                    $province = \App\Models\Address::find($address->parentid);
                    $fullAreaname = ($province ? $province->areaname : '') . $address->areaname;
                } elseif ($address->level == 3) {
                    // 选了区县
                    $city = \App\Models\Address::find($address->parentid);
                    if ($city) {
                        $province = \App\Models\Address::find($city->parentid);
                        $fullAreaname = ($province ? $province->areaname : '') . $city->areaname . $address->areaname;
                    }
                }
            }
        }

        $merchant = Merchant::create([
            'name' => $request->name,
            'code' => $request->code,
            'tax_number' => $request->tax_number,
            'mobile' => $request->mobile,
            'area_id' => $areaId,
            'full_areaname' => $fullAreaname,
            'address' => $request->address,
            'balance' => 0,
            'status' => $request->status ?? 1,
        ]);

        return response()->json([
            'code' => 200,
            'message' => '创建成功',
            'data' => $merchant
        ], 200, ['Content-Type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取机构详情
     */
    public function show($id)
    {
        $merchant = Merchant::with('admins')->findOrFail($id);

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $merchant
        ]);
    }

    /**
     * 更新机构
     */
    public function update(Request $request, $id)
    {
        $merchant = Merchant::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:255',
            'code' => 'nullable|string|max:50',
            'tax_number' => 'nullable|string|max:100',
            'mobile' => 'nullable|string|max:255',
            'district_id' => 'nullable|integer',
            'address' => 'nullable|string|max:255',
            'status' => 'sometimes|integer|in:0,1',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first()
            ], 400);
        }

        $updateData = $request->only([
            'name',
            'code',
            'tax_number',
            'mobile',
            'address',
            'status'
        ]);

        // 更新省市区信息（支持1-3级）
        $areaId = $request->district_id ?: ($request->city_id ?: $request->province_id);
        
        if ($areaId) {
            $address = \App\Models\Address::find($areaId);
            if ($address) {
                $updateData['area_id'] = $areaId;
                
                if ($address->level == 1) {
                    // 只选了省
                    $updateData['full_areaname'] = $address->areaname;
                } elseif ($address->level == 2) {
                    // 选了市
                    $province = \App\Models\Address::find($address->parentid);
                    $updateData['full_areaname'] = ($province ? $province->areaname : '') . $address->areaname;
                } elseif ($address->level == 3) {
                    // 选了区县
                    $city = \App\Models\Address::find($address->parentid);
                    if ($city) {
                        $province = \App\Models\Address::find($city->parentid);
                        $updateData['full_areaname'] = ($province ? $province->areaname : '') . $city->areaname . $address->areaname;
                    }
                }
            }
        }

        $merchant->update($updateData);

        return response()->json([
            'code' => 200,
            'message' => '更新成功',
            'data' => $merchant
        ]);
    }

    /**
     * 删除机构
     */
    public function destroy($id)
    {
        $merchant = Merchant::findOrFail($id);
        $merchant->delete();

        return response()->json([
            'code' => 200,
            'message' => '删除成功'
        ]);
    }

    /**
     * 创建机构管理员
     */
    public function createAdmin(Request $request, $merchantId)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|max:255|unique:merchant_admin',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first()
            ], 400);
        }

        $admin = MerchantAdmin::create([
            'merchant_id' => $merchantId,
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'email' => $request->email,
            'nick_name' => $request->nick_name,
            'status' => 1,
        ]);

        return response()->json([
            'code' => 200,
            'message' => '创建成功',
            'data' => $admin
        ]);
    }

    /**
     * 充值
     */
    public function recharge(Request $request, $merchantId)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:0.01',
            'type' => 'required|integer|in:1,2,3',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first()
            ], 400);
        }

        $merchant = Merchant::findOrFail($merchantId);
        $beforeBalance = $merchant->balance;
        $afterBalance = $beforeBalance + $request->amount;

        // 创建充值记录
        $recharge = \DB::table('ims_yh_merchant_recharges')->insert([
            'merchant_id' => $merchantId,
            'amount' => $request->amount,
            'before_balance' => $beforeBalance,
            'after_balance' => $afterBalance,
            'operator' => $request->user()->username ?? 'admin',
            'note' => $request->note,
        ]);

        // 更新商户余额
        $merchant->balance = $afterBalance;
        $merchant->save();

        return response()->json([
            'code' => 200,
            'message' => '充值成功',
            'data' => [
                'before_balance' => $beforeBalance,
                'after_balance' => $afterBalance
            ]
        ]);
    }

    /**
     * 获取充值记录
     */
    public function rechargeList(Request $request)
    {
        $query = \DB::table('ims_yh_merchant_recharges')
            ->join('ims_yh_merchant', 'ims_yh_merchant_recharges.merchant_id', '=', 'ims_yh_merchant.id')
            ->select('ims_yh_merchant_recharges.*', 'ims_yh_merchant.name as merchant_name');

        if ($request->has('merchant_id')) {
            $query->where('ims_yh_merchant_recharges.merchant_id', $request->merchant_id);
        }

        if ($request->has('start_date')) {
            $query->where('ims_yh_merchant_recharges.created_at', '>=', $request->start_date);
        }

        if ($request->has('end_date')) {
            $query->where('ims_yh_merchant_recharges.created_at', '<=', $request->end_date);
        }

        $recharges = $query->orderBy('ims_yh_merchant_recharges.created_at', 'desc')
            ->paginate($request->get('pageSize', 10));

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $recharges
        ]);
    }

    /**
     * 获取所有可用的权限列表（菜单列表）
     */
    public function getMenuList()
    {
        // 从数据库表ims_yh_merchant_menu获取权限列表
        $menuList = DB::table('ims_yh_merchant_menu')->get();

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $menuList
        ]);
    }

    /**
     * 获取机构权限（菜单权限）
     */
    public function getPermissions($merchantId)
    {
        $menuRelation = DB::table('ims_yh_merchant_menu_relation')
            ->where('merchant_id', $merchantId)
            ->first();

        $menuCodes = [];
        if ($menuRelation && $menuRelation->menu_code) {
            $menuCodes = explode(',', $menuRelation->menu_code);
        }

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $menuCodes
        ]);
    }

    /**
     * 更新机构权限（菜单权限）
     */
    public function updatePermissions(Request $request, $merchantId)
    {
        $validator = Validator::make($request->all(), [
            'menu_codes' => 'required|array',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first()
            ], 400);
        }

        $menuCode = implode(',', $request->menu_codes);

        // 检查是否已存在
        $exists = DB::table('ims_yh_merchant_menu_relation')
            ->where('merchant_id', $merchantId)
            ->exists();

        if ($exists) {
            // 更新
            DB::table('ims_yh_merchant_menu_relation')
                ->where('merchant_id', $merchantId)
                ->update([
                    'menu_code' => $menuCode,
                ]);
        } else {
            // 插入
            DB::table('ims_yh_merchant_menu_relation')->insert([
                'merchant_id' => $merchantId,
                'menu_code' => $menuCode,
            ]);
        }

        return response()->json([
            'code' => 200,
            'message' => '更新成功'
        ]);
    }

    /**
     * 获取商户管理员列表
     */
    public function adminList(Request $request)
    {
        $query = MerchantAdmin::with('merchant');

        if ($request->has('merchant_id')) {
            $query->where('merchant_id', $request->merchant_id);
        }

        if ($request->has('username')) {
            $query->where('username', 'like', '%' . $request->username . '%');
        }

        $pageSize = $request->get('pageSize', 10);
        $pageNum = $request->get('pageNum', 1);

        // 按创建时间倒序排列
        $admins = $query->orderBy('created_at', 'desc')
            ->paginate($pageSize, ['*'], 'page', $pageNum);

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $admins
        ], 200, ['Content-Type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 创建商户管理员
     */
    public function createMerchantAdmin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'merchant_id' => 'required|exists:ims_yh_merchant,id',
            'username' => 'required|string|max:255|unique:ims_yh_merchant_admin,username',
            'password' => 'required|string|min:6',
        ], [
            'merchant_id.required' => '请选择所属机构',
            'merchant_id.exists' => '所选机构不存在',
            'username.required' => '请输入用户名',
            'username.unique' => '该用户名已被使用，请更换其他用户名',
            'username.max' => '用户名不能超过255个字符',
            'password.required' => '请输入密码',
            'password.min' => '密码长度不能少于6位',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first()
            ], 400);
        }

        $admin = MerchantAdmin::create([
            'merchant_id' => $request->merchant_id,
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'email' => $request->email,
            'nick_name' => $request->nick_name,
            'status' => 1,
        ]);

        // 自动创建管理员角色关联记录，默认角色ID为1
        DB::table('ims_yh_merchant_admin_role_relation')->insert([
            'admin_id' => $admin->id,
            'role_ids' => '1',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'code' => 200,
            'message' => '创建成功',
            'data' => $admin
        ], 200, ['Content-Type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 更新商户管理员
     */
    public function updateMerchantAdmin(Request $request, $id)
    {
        $admin = MerchantAdmin::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'username' => 'sometimes|required|string|max:255|unique:ims_yh_merchant_admin,username,' . $id,
        ], [
            'username.required' => '请输入用户名',
            'username.unique' => '该用户名已被使用，请更换其他用户名',
            'username.max' => '用户名不能超过255个字符',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'message' => $validator->errors()->first()
            ], 400);
        }

        if ($request->has('password') && $request->password) {
            $request->merge(['password' => Hash::make($request->password)]);
        } else {
            $request->request->remove('password');
        }

        $admin->update($request->all());

        return response()->json([
            'code' => 200,
            'message' => '更新成功',
            'data' => $admin
        ], 200, ['Content-Type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 删除商户管理员
     */
    public function deleteMerchantAdmin($id)
    {
        $admin = MerchantAdmin::findOrFail($id);
        $admin->delete();

        return response()->json([
            'code' => 200,
            'message' => '删除成功'
        ], 200, ['Content-Type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 更新商户管理员状态
     */
    public function updateMerchantAdminStatus(Request $request, $id)
    {
        $admin = MerchantAdmin::findOrFail($id);
        $admin->status = $request->status;
        $admin->save();

        return response()->json([
            'code' => 200,
            'message' => '更新成功'
        ], 200, ['Content-Type' => 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取省市区列表API
     */
    public function getAddresses(Request $request)
    {
        try {
            $level = $request->get('level', 1); // 1-省份，2-城市，3-区县
            $parentId = $request->get('parent_id'); // 父级ID
            $districtId = $request->get('district_id'); // 区县ID（用于反向查询）

            // 如果提供了district_id，返回完整的省市区信息
            if ($districtId) {
                $address = \App\Models\Address::find($districtId);
                if (!$address) {
                    return response()->json([
                        'code' => 404,
                        'message' => '地址不存在'
                    ], 404);
                }

                $result = [
                    'province_id' => null,
                    'city_id' => null,
                    'district_id' => null,
                    'cities' => [],
                    'districts' => []
                ];

                // 根据level判断是省、市还是区
                if ($address->level == 1) {
                    // 只保存了省
                    $result['province_id'] = $address->id;
                    // 获取该省的所有城市
                    $result['cities'] = \App\Models\Address::where('level', 2)
                        ->where('parentid', $address->id)
                        ->orderBy('id')
                        ->get(['id', 'areaname'])
                        ->map(function ($item) {
                            return [
                                'id' => $item->id,
                                'name' => $item->areaname
                            ];
                        });
                } elseif ($address->level == 2) {
                    // 保存了市
                    $result['city_id'] = $address->id;
                    $province = \App\Models\Address::find($address->parentid);
                    if ($province) {
                        $result['province_id'] = $province->id;
                        // 获取该省的所有城市
                        $result['cities'] = \App\Models\Address::where('level', 2)
                            ->where('parentid', $province->id)
                            ->orderBy('id')
                            ->get(['id', 'areaname'])
                            ->map(function ($item) {
                                return [
                                    'id' => $item->id,
                                    'name' => $item->areaname
                                ];
                            });
                    }
                } elseif ($address->level == 3) {
                    // 保存了区县
                    $result['district_id'] = $address->id;
                    $city = \App\Models\Address::find($address->parentid);
                    if ($city) {
                        $result['city_id'] = $city->id;
                        $province = \App\Models\Address::find($city->parentid);
                        if ($province) {
                            $result['province_id'] = $province->id;
                            // 获取该省的所有城市
                            $result['cities'] = \App\Models\Address::where('level', 2)
                                ->where('parentid', $province->id)
                                ->orderBy('id')
                                ->get(['id', 'areaname'])
                                ->map(function ($item) {
                                    return [
                                        'id' => $item->id,
                                        'name' => $item->areaname
                                    ];
                                });
                        }
                        // 获取该市的所有区县
                        $result['districts'] = \App\Models\Address::where('level', 3)
                            ->where('parentid', $city->id)
                            ->orderBy('id')
                            ->get(['id', 'areaname'])
                            ->map(function ($item) {
                                return [
                                    'id' => $item->id,
                                    'name' => $item->areaname
                                ];
                            });
                    }
                }

                return response()->json([
                    'code' => 200,
                    'message' => 'success',
                    'data' => $result
                ]);
            }

            $query = \App\Models\Address::where('level', $level);

            // 如果有父级ID，则添加条件
            if ($parentId) {
                $query->where('parentid', $parentId);
            }

            $addresses = $query->orderBy('id')->get(['id', 'areaname'])->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->areaname
                ];
            });

            return response()->json([
                'code' => 200,
                'message' => 'success',
                'data' => $addresses
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '获取地址列表失败：' . $e->getMessage()
            ], 500);
        }
    }
}
